<!DOCTYPE html>
<html lang="en">
    <!-- title -->




<!-- keywords -->




<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" >
    <meta name="author" content="驿路星辰">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="驿路星辰">
    
    <meta name="keywords" content="算法,Swift,Dart,iOS,Flutter,C++">
    
    <meta name="description" content="">
    <meta name="description" content="MVVM介绍MVVM架构分为M(Model)、V(View)、VM(ViewModel)三个部分，他们分别处理自己的分工，在View和Model之间使用ViewModel作为中介者，使View和Model不受业务逻辑影响。 Model: 模型层，处理Api数据、模型相关业务 View: 视图层，UI呈现、使用者互动等。 ViewModel: 视图模型，处理逻辑、将数据绑定给View展示。 Cont">
<meta property="og:type" content="article">
<meta property="og:title" content="Flutter中使用Provider实现MVVM架构">
<meta property="og:url" content="http://kurumi.gitee.io/shanks/2020/08/29/flutter-mvvm/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="MVVM介绍MVVM架构分为M(Model)、V(View)、VM(ViewModel)三个部分，他们分别处理自己的分工，在View和Model之间使用ViewModel作为中介者，使View和Model不受业务逻辑影响。 Model: 模型层，处理Api数据、模型相关业务 View: 视图层，UI呈现、使用者互动等。 ViewModel: 视图模型，处理逻辑、将数据绑定给View展示。 Cont">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-08-29T01:10:14.000Z">
<meta property="article:modified_time" content="2022-05-02T05:51:49.849Z">
<meta property="article:author" content="驿路星辰">
<meta name="twitter:card" content="summary">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    
    <title>Flutter中使用Provider实现MVVM架构 · iOS</title>
    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/shanks/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 30vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }

</style>

    <link rel="preload" href= "/shanks/css/style.css?v=20180824" as="style" onload="this.onload=null;this.rel='stylesheet'" />
    <link rel="stylesheet" href= "/shanks/css/mobile.css?v=20180824" media="(max-width: 980px)">
    
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'" />
    
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
(function( w ){
	"use strict";
	// rel=preload support test
	if( !w.loadCSS ){
		w.loadCSS = function(){};
	}
	// define on the loadCSS obj
	var rp = loadCSS.relpreload = {};
	// rel=preload feature support test
	// runs once and returns a function for compat purposes
	rp.support = (function(){
		var ret;
		try {
			ret = w.document.createElement( "link" ).relList.supports( "preload" );
		} catch (e) {
			ret = false;
		}
		return function(){
			return ret;
		};
	})();

	// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
	// then change that media back to its intended value on load
	rp.bindMediaToggle = function( link ){
		// remember existing media attr for ultimate state, or default to 'all'
		var finalMedia = link.media || "all";

		function enableStylesheet(){
			link.media = finalMedia;
		}

		// bind load handlers to enable media
		if( link.addEventListener ){
			link.addEventListener( "load", enableStylesheet );
		} else if( link.attachEvent ){
			link.attachEvent( "onload", enableStylesheet );
		}

		// Set rel and non-applicable media type to start an async request
		// note: timeout allows this to happen async to let rendering continue in IE
		setTimeout(function(){
			link.rel = "stylesheet";
			link.media = "only x";
		});
		// also enable media after 3 seconds,
		// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
		setTimeout( enableStylesheet, 3000 );
	};

	// loop through link elements in DOM
	rp.poly = function(){
		// double check this to prevent external calls from running
		if( rp.support() ){
			return;
		}
		var links = w.document.getElementsByTagName( "link" );
		for( var i = 0; i < links.length; i++ ){
			var link = links[ i ];
			// qualify links to those with rel=preload and as=style attrs
			if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){
				// prevent rerunning on link
				link.setAttribute( "data-loadcss", true );
				// bind listeners to toggle media back
				rp.bindMediaToggle( link );
			}
		}
	};

	// if unsupported, run the polyfill
	if( !rp.support() ){
		// run once at least
		rp.poly();

		// rerun poly on an interval until onload
		var run = w.setInterval( rp.poly, 500 );
		if( w.addEventListener ){
			w.addEventListener( "load", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		} else if( w.attachEvent ){
			w.attachEvent( "onload", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		}
	}


	// commonjs
	if( typeof exports !== "undefined" ){
		exports.loadCSS = loadCSS;
	}
	else {
		w.loadCSS = loadCSS;
	}
}( typeof global !== "undefined" ? global : this ) );
</script>

    <link rel="icon" href= "/shanks/assets/favicon.ico" />
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js" as="script" />
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js" as="script" />
    <link rel="preload" href="/shanks/scripts/main.js" as="script" />
    <link rel="preload" as="font" href="/shanks/font/Oswald-Regular.ttf" crossorigin>
    <link rel="preload" as="font" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" crossorigin>
    
    <!-- fancybox -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" defer></script>
    <!-- 百度统计  -->
    
    <!-- 谷歌统计  -->
    
<meta name="generator" content="Hexo 4.2.1"></head>

    
        <body class="post-body">
    
    
<header class="header">

    <div class="read-progress"></div>
    <div class="header-sidebar-menu">&#xe775;</div>
    <!-- post页的toggle banner  -->
    
    <div class="banner">
            <div class="blog-title">
                <a href="/shanks/" >驿路星辰的博客</a>
            </div>
            <div class="post-title">
                <a href="#" class="post-name">Flutter中使用Provider实现MVVM架构</a>
            </div>
    </div>
    
    <a class="home-link" href=/shanks/>驿路星辰的博客</a>
</header>
    <div class="wrapper">
        <div class="site-intro" style="







height:50vh;
">
    
    <!-- 主页  -->
    
    
    <!-- 404页  -->
            
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(/shanks/intro/post-bg.jpg)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
            Flutter中使用Provider实现MVVM架构
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
            
            <!-- 404 -->
            
        </p>
        <!-- 文章页meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                
                    <div class="post-intro-read">
                        <span>Word count: <span class="post-count word-count">871</span>Reading time: <span class="post-count reading-time">4 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <span class="post-intro-calander iconfont-archer">&#xe676;</span>
                    <span class="post-intro-time">2020/08/29</span>
                    
                    <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                        <span class="iconfont-archer">&#xe602;</span>
                        <span id="busuanzi_value_page_pv"></span>
                    </span>
                    
                    <span class="shareWrapper">
                        <span class="iconfont-archer shareIcon">&#xe71d;</span>
                        <span class="shareText">Share</span>
                        <ul class="shareList">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>
        <script>
 
  // get user agent
  var browser = {
    versions: function () {
      var u = window.navigator.userAgent;
      return {
        userAgent: u,
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
        iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
        iPad: u.indexOf('iPad') > -1, //是否为iPad
        webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
        uc: u.indexOf('UCBrowser') > -1 //是否为android下的UC浏览器
      };
    }()
  }
  console.log("userAgent:" + browser.versions.userAgent);

  // callback
  function fontLoaded() {
    console.log('font loaded');
    if (document.getElementsByClassName('site-intro-meta')) {
      document.getElementsByClassName('intro-title')[0].classList.add('intro-fade-in');
      document.getElementsByClassName('intro-subtitle')[0].classList.add('intro-fade-in');
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in');
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb(){
    if (browser.versions.uc) {
      console.log("UCBrowser");
      fontLoaded();
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular']
        },
        loading: function () {  //所有字体开始加载
          // console.log('loading');
        },
        active: function () {  //所有字体已渲染
          fontLoaded();
        },
        inactive: function () { //字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout');
          fontLoaded();
        },
        timeout: 5000 // Set the timeout to two seconds
      });
    }
  }

  function asyncErr(){
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (cb) { o.addEventListener('load', function (e) { cb(null, e); }, false); }
    if (err) { o.addEventListener('error', function (e) { err(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }

  var asyncLoadWithFallBack = function(arr, success, reject) {
      var currReject = function(){
        reject()
        arr.shift()
        if(arr.length)
          async(arr[0], success, currReject)
        }

      async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack([
    "https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js", 
    "https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js",
    "/shanks/lib/webfontloader.min.js"
  ], asyncCb, asyncErr)
</script>        
        <img class="loading" src="/shanks/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
        <div class="container container-unloaded">
            <main class="main post-page">
    <article class="article-entry">
        <h1 id="MVVM介绍"><a href="#MVVM介绍" class="headerlink" title="MVVM介绍"></a>MVVM介绍</h1><p>MVVM架构分为M(Model)、V(View)、VM(ViewModel)三个部分，他们分别处理自己的分工，在View和Model之间使用ViewModel作为中介者，使View和Model不受业务逻辑影响。</p>
<p><strong>Model</strong>: 模型层，处理Api数据、模型相关业务</p>
<p><strong>View</strong>: 视图层，UI呈现、使用者互动等。</p>
<p><strong>ViewModel</strong>: 视图模型，处理逻辑、将数据绑定给View展示。</p>
<p><strong>Controller</strong>: 负责主要事情就是将View和ViewModel进行绑定，生命周期管理</p>
<p>MVVM的核心思想即：通过ViewModel在View和Model之间建立一个连接，实现View和Model的双向绑定。</p>
<hr>
<h1 id="Flutter中的MVVM应用"><a href="#Flutter中的MVVM应用" class="headerlink" title="Flutter中的MVVM应用"></a>Flutter中的MVVM应用</h1><p>Flutter中通过<code>Provider</code>进行状态管理，来实现MVVM。在MVVM的原本的三个部分添加Services层，方便业务的分离.</p>
<p>Services: 是获取数据接口（服务器Server 或者 本地Store）</p>
<p>Model: 主要负责转换模型</p>
<p>View: 主要负责呈现UI，通过ViewModel获取数据并展示</p>
<p>ViewModel: 处理业务逻辑，将数据绑定给View展示</p>
<p>Controller:一般是stf，负责主要事情就是将View和ViewModel进行绑定，生命周期管理</p>
<hr>
<h2 id="1-定义模型"><a href="#1-定义模型" class="headerlink" title="1.定义模型"></a>1.定义模型</h2><p>将网络请求回来的数据转换为对应的模型</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DeviceOnlineStatusData</span> </span>&#123;</span><br><span class="line">  <span class="built_in">String</span> deviceId;</span><br><span class="line">  <span class="built_in">String</span> deviceType;</span><br><span class="line">  <span class="built_in">String</span> loginTime;</span><br><span class="line">  <span class="built_in">String</span> createdAt;</span><br><span class="line"></span><br><span class="line">  DeviceOnlineStatusData(&#123;<span class="keyword">this</span>.deviceId, <span class="keyword">this</span>.deviceType, <span class="keyword">this</span>.loginTime, <span class="keyword">this</span>.createdAt&#125;);</span><br><span class="line"></span><br><span class="line">  DeviceOnlineStatusData.fromJson(<span class="built_in">Map</span>&lt;<span class="built_in">String</span>, <span class="built_in">dynamic</span>&gt; json) &#123;</span><br><span class="line">    deviceId = json[<span class="string">'device_id'</span>];</span><br><span class="line">    deviceType = json[<span class="string">'device_type'</span>];</span><br><span class="line">    loginTime = json[<span class="string">'login_time'</span>];</span><br><span class="line">    createdAt = json[<span class="string">'created_at'</span>];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">Map</span>&lt;<span class="built_in">String</span>, <span class="built_in">dynamic</span>&gt; toJson() &#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="built_in">Map</span>&lt;<span class="built_in">String</span>, <span class="built_in">dynamic</span>&gt; data = <span class="keyword">new</span> <span class="built_in">Map</span>&lt;<span class="built_in">String</span>, <span class="built_in">dynamic</span>&gt;();</span><br><span class="line">    data[<span class="string">'device_id'</span>] = <span class="keyword">this</span>.deviceId;</span><br><span class="line">    data[<span class="string">'device_type'</span>] = <span class="keyword">this</span>.deviceType;</span><br><span class="line">    data[<span class="string">'login_time'</span>] = <span class="keyword">this</span>.loginTime;</span><br><span class="line">    data[<span class="string">'created_at'</span>] = <span class="keyword">this</span>.createdAt;</span><br><span class="line">    <span class="keyword">return</span> data;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-定义ViewModel"><a href="#2-定义ViewModel" class="headerlink" title="2.定义ViewModel"></a>2.定义ViewModel</h2><p>这个ViewModel主要负责把请求回来的数据进行处理，并通知View层更新数据</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DeviceOnlineStatusVM</span> <span class="keyword">extends</span> <span class="title">ChangeNotifier</span> </span>&#123;</span><br><span class="line">  <span class="built_in">bool</span> isPcLogin = <span class="keyword">false</span>;</span><br><span class="line">  <span class="built_in">bool</span> isPadLogin = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">String</span> pcDeviceID = <span class="string">''</span>;</span><br><span class="line">  <span class="built_in">String</span> pcDeviceType = <span class="string">''</span>;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">String</span> padDeviceID = <span class="string">''</span>;</span><br><span class="line">  <span class="built_in">String</span> padDeviceType = <span class="string">''</span>;</span><br><span class="line"></span><br><span class="line">  setOnlineStatus(<span class="built_in">List</span>&lt;DeviceOnlineStatusData&gt; statusData) &#123;</span><br><span class="line">    init();</span><br><span class="line">    isPcLogin = <span class="keyword">true</span>;</span><br><span class="line">    pcDeviceID = item.deviceId;</span><br><span class="line">    pcDeviceType = item.deviceType;</span><br><span class="line">    isPadLogin = <span class="keyword">true</span>;</span><br><span class="line">    padDeviceID = item.deviceId;</span><br><span class="line">    padDeviceType = item.deviceType;</span><br><span class="line">    notifyListeners();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">void</span> init() &#123;</span><br><span class="line">    isPcLogin = <span class="keyword">false</span>;</span><br><span class="line">    isPadLogin = <span class="keyword">false</span>;</span><br><span class="line">    pcDeviceID = <span class="string">''</span>;</span><br><span class="line">    pcDeviceType = <span class="string">''</span>;</span><br><span class="line">    padDeviceID = <span class="string">''</span>;</span><br><span class="line">    padDeviceType = <span class="string">''</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3-定义网络请求类"><a href="#3-定义网络请求类" class="headerlink" title="3.定义网络请求类"></a>3.定义网络请求类</h2><p>网络请求将请求回来的数据转换为模型，并更新ViewModel数据。通过extension进行横向拓展</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">extension</span> DeviceOnlineStatusServices <span class="keyword">on</span> DeviceOnlineStatusVM &#123;</span><br><span class="line">  <span class="comment">//获取设备状态</span></span><br><span class="line">  Future&lt;<span class="keyword">void</span>&gt; getOnlineStatusServices() <span class="keyword">async</span> &#123;</span><br><span class="line">    HttpResp httpResp = <span class="keyword">await</span> HttpApi().getOnlineStatus();</span><br><span class="line">    <span class="keyword">if</span> (httpResp.code == <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="built_in">List</span> jsonList = httpResp.value;</span><br><span class="line">      <span class="built_in">List</span>&lt;DeviceOnlineStatusData&gt; statusData = jsonList.map((e) =&gt; DeviceOnlineStatusData.fromJson(e)).toList();</span><br><span class="line">      setOnlineStatus(statusData);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//更新设备状态</span></span><br><span class="line">  Future&lt;<span class="keyword">void</span>&gt; setOnlineStatusServices(<span class="built_in">String</span> deviceID, <span class="built_in">String</span> deviceType) <span class="keyword">async</span> &#123;</span><br><span class="line">    HttpResp httpResp = <span class="keyword">await</span> HttpApi().postOnlineStatus(deviceID, deviceType);</span><br><span class="line">    <span class="keyword">if</span> (httpResp.code == <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="built_in">List</span> jsonList = httpResp.value;</span><br><span class="line">      <span class="built_in">List</span>&lt;DeviceOnlineStatusData&gt; statusData = jsonList.map((e) =&gt; DeviceOnlineStatusData.fromJson(e)).toList();</span><br><span class="line">      setOnlineStatus(statusData);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h2 id="4-View数据展示层"><a href="#4-View数据展示层" class="headerlink" title="4.View数据展示层"></a>4.View数据展示层</h2><p>单独抽出View层，View用来渲染数据</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DeviceOnlineStatusView</span> <span class="keyword">extends</span> <span class="title">StatelessWidget</span> </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> DeviceOnlineStatusView(&#123;Key key, <span class="keyword">this</span>.viewModel&#125;) : <span class="keyword">super</span>(key: key);</span><br><span class="line">  <span class="keyword">final</span> DeviceOnlineStatusVM viewModel;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  Widget build(BuildContext context) &#123;</span><br><span class="line">    <span class="keyword">return</span> Flex(</span><br><span class="line">      direction: Axis.vertical,</span><br><span class="line">      children: &lt;Widget&gt;[</span><br><span class="line">         Column(</span><br><span class="line">            crossAxisAlignment: CrossAxisAlignment.center,</span><br><span class="line">            mainAxisAlignment: MainAxisAlignment.center,</span><br><span class="line">            children: &lt;Widget&gt;[</span><br><span class="line">              Row(</span><br><span class="line">                mainAxisAlignment: MainAxisAlignment.center,</span><br><span class="line">                children: &lt;Widget&gt;[Image.asset(<span class="string">"assets/images/im_device_pc.png"</span>, width: <span class="number">178</span>, height: <span class="number">92</span>)],</span><br><span class="line">              ),            </span><br><span class="line">              <span class="keyword">const</span> SizedBox(height: <span class="number">14.0</span>),</span><br><span class="line">              Row(</span><br><span class="line">                mainAxisAlignment: MainAxisAlignment.center,</span><br><span class="line">                children: &lt;Widget&gt;[</span><br><span class="line">                    TextImageButtonWidget(</span><br><span class="line">                      text: <span class="string">"退出"</span>,</span><br><span class="line">                      normalImage: <span class="string">"im_device_back.png"</span>,</span><br><span class="line">                      disableImage: <span class="string">"im_device_back_disable.png"</span>,</span><br><span class="line">                      buttonEnable: viewModel.isPcLogin,</span><br><span class="line">                      onTapCallBack: () &#123;</span><br><span class="line">                        Utils.showCommonDialog(context: context, content: <span class="string">'是否退出电脑登录?'</span>).then((value) <span class="keyword">async</span> &#123;</span><br><span class="line">                          <span class="keyword">if</span> (value) &#123;</span><br><span class="line">                            viewModel</span><br><span class="line">                                .setOnlineStatusServices(viewModel.pcDeviceID, viewModel.padDeviceType)</span><br><span class="line">                                .then((value) &#123;</span><br><span class="line">                              <span class="keyword">if</span> (!viewModel.isPadLogin &amp;&amp; !viewModel.isPcLogin) &#123;</span><br><span class="line">                                Utils.popPage();</span><br><span class="line">                              &#125;</span><br><span class="line">                            &#125;);</span><br><span class="line">                          &#125;</span><br><span class="line">                        &#125;);</span><br><span class="line">                      &#125;),</span><br><span class="line">                ],</span><br><span class="line">              ),</span><br><span class="line">            ],</span><br><span class="line">          ),       </span><br><span class="line">      ],</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-Controller用来将viewModel绑定View，并且管理生命周期"><a href="#5-Controller用来将viewModel绑定View，并且管理生命周期" class="headerlink" title="5.Controller用来将viewModel绑定View，并且管理生命周期"></a>5.Controller用来将viewModel绑定View，并且管理生命周期</h2><figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DeviceOnlineStatusPage</span> <span class="keyword">extends</span> <span class="title">StatefulWidget</span> </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> DeviceOnlineStatusPage(&#123;</span><br><span class="line">    Key key,</span><br><span class="line">    <span class="keyword">this</span>.title,</span><br><span class="line">    <span class="keyword">this</span>.deviceOnlineStatusVM,</span><br><span class="line">  &#125;) : <span class="keyword">super</span>(key: key);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">final</span> <span class="built_in">String</span> title;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">final</span> DeviceOnlineStatusVM deviceOnlineStatusVM;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  State&lt;StatefulWidget&gt; createState() =&gt; _DeviceOnlineStatusPage();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">_DeviceOnlineStatusPage</span> <span class="keyword">extends</span> <span class="title">State</span>&lt;<span class="title">DeviceOnlineStatusPage</span>&gt; </span>&#123;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  <span class="keyword">void</span> initState() &#123;</span><br><span class="line">    <span class="comment">// 获取接口数据</span></span><br><span class="line">    widget.deviceOnlineStatusVM.getOnlineStatusServices();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">super</span>.initState();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  Widget build(BuildContext context) &#123;</span><br><span class="line">    <span class="keyword">return</span> Scaffold(</span><br><span class="line">      appBar: NavigationAppBar(title: widget.title),</span><br><span class="line">      body: ChangeNotifierProvider.value(</span><br><span class="line">        value: widget.deviceOnlineStatusVM,</span><br><span class="line">        child: Consumer&lt;DeviceOnlineStatusVM&gt;(</span><br><span class="line">          builder: (context, _viewModel, _) &#123;</span><br><span class="line">            <span class="keyword">return</span> DeviceOnlineStatusView(viewModel: _viewModel);</span><br><span class="line">          &#125;,</span><br><span class="line">        ),</span><br><span class="line">      ),</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
    </article>
    <!-- license  -->
    
        <div class="license-wrapper">
            <p>Author：<a href="http://kurumi.gitee.io/shanks">驿路星辰</a>
            <p>原文链接：<a href="http://kurumi.gitee.io/shanks/2020/08/29/flutter-mvvm/">http://kurumi.gitee.io/shanks/2020/08/29/flutter-mvvm/</a>
            <p>发表日期：<a href="http://kurumi.gitee.io/shanks/2020/08/29/flutter-mvvm/">August 29th 2020</a>
            <p>更新日期：<a href="http://kurumi.gitee.io/shanks/2020/08/29/flutter-mvvm/">August 29th 2020</a>
            <p>版权声明：本文采用<a rel="license noopener" href="http://creativecommons.org/licenses/by-nc/4.0/" target="_blank">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator  -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href= "/shanks/2020/08/29/flutter-ios-plugin-delegate-error/" title= "Flutter中针对iOS封装Plugin组件注意事项">
                    <div class="nextTitle">Flutter中针对iOS封装Plugin组件注意事项</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href= "/shanks/2020/06/07/crypt-night/" title= "9.SSL/TLS(为了更安全的通信)---《图解密码学》">
                    <div class="prevTitle">9.SSL/TLS(为了更安全的通信)---《图解密码学》</div>
                </a>
            
        </li>
    </ul>
    <!-- 评论插件 -->
    <!-- 来必力City版安装代码 -->

<!-- City版安装代码已完成 -->
    
    
    <!-- gitalk评论 -->

    <!-- utteranc评论 -->

    <!-- partial('_partial/comment/changyan') -->
    <!--PC版-->


    
    

    <!-- 评论 -->
</main>
            <!-- profile -->
            
        </div>
        <footer class="footer footer-unloaded">
    <!-- social  -->
    
    <div class="social">
        
    
        
            
                <a href="mailto:ayaseeri@126.com" class="iconfont-archer email" title=email ></a>
            
        
    
        
            
                <a href="//github.com/esdeath" class="iconfont-archer github" target="_blank" title=github></a>
            
        
    
        
    
        
    

    </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <!-- 不蒜子  -->
    
    <div class="busuanzi-container">
    
     
    <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
    
    </div>
    
</footer>
    </div>
    <!-- toc -->
    
    <div class="toc-wrapper" style=
    







top:50vh;

    >
        <div class="toc-catalog">
            <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
        </div>
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#MVVM介绍"><span class="toc-number">1.</span> <span class="toc-text">MVVM介绍</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Flutter中的MVVM应用"><span class="toc-number">2.</span> <span class="toc-text">Flutter中的MVVM应用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-定义模型"><span class="toc-number">2.1.</span> <span class="toc-text">1.定义模型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-定义ViewModel"><span class="toc-number">2.2.</span> <span class="toc-text">2.定义ViewModel</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-定义网络请求类"><span class="toc-number">2.3.</span> <span class="toc-text">3.定义网络请求类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-View数据展示层"><span class="toc-number">2.4.</span> <span class="toc-text">4.View数据展示层</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-Controller用来将viewModel绑定View，并且管理生命周期"><span class="toc-number">2.5.</span> <span class="toc-text">5.Controller用来将viewModel绑定View，并且管理生命周期</span></a></li></ol></li></ol>
    </div>
    
    <div class="back-top iconfont-archer">&#xe639;</div>
    <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
          <div class="sidebar-panel-archives">
    <!-- 在ejs中将archive按照时间排序 -->
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 16
        </div>
        <!-- search  -->
        
    </div>
    
    <div class="post-archive">
    
    
    
    
    <div class="archive-year"> 2020 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/29</span><a class="archive-post-title" href= "/shanks/2020/08/29/flutter-ios-plugin-delegate-error/" >Flutter中针对iOS封装Plugin组件注意事项</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/29</span><a class="archive-post-title" href= "/shanks/2020/08/29/flutter-mvvm/" >Flutter中使用Provider实现MVVM架构</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/07</span><a class="archive-post-title" href= "/shanks/2020/06/07/crypt-night/" >9.SSL/TLS(为了更安全的通信)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/31</span><a class="archive-post-title" href= "/shanks/2020/05/31/crypt-eight/" >8.证书(为公钥加上数字签名)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/29</span><a class="archive-post-title" href= "/shanks/2020/05/29/crypt-seven/" >7.数字签名(消息到底是谁写的)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/21</span><a class="archive-post-title" href= "/shanks/2020/05/21/crypt-six/" >6.消息认证码(消息被正确传送了吗)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/12</span><a class="archive-post-title" href= "/shanks/2020/05/12/crypt-five-md/" >5.单向散列函数(获取消息的指纹)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/08</span><a class="archive-post-title" href= "/shanks/2020/05/08/crypt-four-md/" >4.非对称加密(公钥加密,私钥解密)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/05</span><a class="archive-post-title" href= "/shanks/2020/05/05/crypt-three-md/" >3. 分组密码的模式(分组密码是如何迭代)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">04/30</span><a class="archive-post-title" href= "/shanks/2020/04/30/crypt-two-md/" >2.对称加密（相同密钥加解密)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">04/29</span><a class="archive-post-title" href= "/shanks/2020/04/29/crypt-one-md/" >1.密码学 ---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/27</span><a class="archive-post-title" href= "/shanks/2020/03/27/ios-gcd-ptread/" >iOS 90%人可能都会回答错误的一个多线程基础题</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/27</span><a class="archive-post-title" href= "/shanks/2020/01/27/how-to-know-highorlow-computer-md/" >如何判断机器的字节顺序是高字节在前还是低字节在前</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2019 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">10/11</span><a class="archive-post-title" href= "/shanks/2019/10/11/swift-function-program/" >【译】Swift和函数式编程的精髓</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">10/03</span><a class="archive-post-title" href= "/shanks/2019/10/03/how-to-use-functional-program-in-swift/" >【译】如何在swift中使用函数式编程</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/28</span><a class="archive-post-title" href= "/shanks/2019/08/28/swift-operator-override/" >【译】如何在swift中使用函数式编程</a>
        </li>
    
    </div>
  </div>
        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
    
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
    缺失模块。<br/>
    1、请确保node版本大于6.2<br/>
    2、在博客根目录（注意不是archer根目录）执行以下命令：<br/>
    <span style="color: #f75357; font-size: 1rem; line-height: 2rem;">npm i hexo-generator-json-content --save</span><br/>
    3、在根目录_config.yml里添加配置：
    <pre style="color: #787878; font-size: 0.6rem;">
jsonContent:
  meta: false
  pages: false
  posts:
    title: true
    date: true
    path: true
    text: false
    raw: false
    content: false
    slug: false
    updated: false
    comments: false
    link: false
    permalink: false
    excerpt: false
    categories: true
    tags: true</pre>
    </div> 
    <div class="sidebar-tags-list"></div>
</div>
        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>
    </div>
</div> 
    <script>
    var siteMeta = {
        root: "/shanks/",
        author: "驿路星辰"
    }
</script>
    <!-- CDN failover -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ === 'undefined')
        {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/shanks/lib/jquery.min.js">\x3C/script>')
        }
    </script>
    <script src="/shanks/scripts/main.js"></script>
    <!-- algolia -->
    
    <!-- busuanzi  -->
    
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    
    <!-- CNZZ  -->
    
    </div>
    <!-- async load share.js -->
    
        <script src="/shanks/scripts/share.js" async></script>    
     
    </body>
</html>


